<template>
  <div class="container">
    <div class="app-container">
      <!-- 添加角色按钮 -->
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="showDialog=true">添加角色</el-button>
      </div>
      <!-- 数据表格 -->
      <el-table :data="list">
        <el-table-column prop="name" width="200px" label="角色" align="center">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRole.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" width="200px" label="启用" align="center">
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRole.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else>{{ row.state===1? "已启用" : row.state=== 0? "未启用":"无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRole.description" type="textarea" :rows="3" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnEditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editRole(row)">编辑</el-button>
              <el-popconfirm title="这是一条角色信息确定删除吗？" style="margin-left:10px;" @onConfirm="delRole(row.id)">
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" height="60px" justify="end" align="middle">
        <el-pagination :total="pageParams.total" :page-size="pageParams.pagesize" :current-page="pageParams.page" layout="prev, pager, next" @current-change="pageChange" />
      </el-row>
    </div>
    <!-- 弹框 -->
    <el-dialog title="添加角色" width="500px" :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="ruleForm">
        <el-form-item prop="name" label="角色名称" size="mini">
          <el-input v-model="roleForm.name" style="width:300px" />
        </el-form-item>
        <el-form-item prop="state" label="启用" size="mini">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" style="width:300px" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述" size="mini">
          <el-input v-model="roleForm.description" style="width:300px" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="center">
        <el-col :span="7">
          <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
          <el-button size="mini" @click="btnCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 分配权限弹窗 -->
    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <el-tree ref="permTree" check-strictly :data="permissionList" :props="{label:'name'}" default-expand-all show-checkbox :default-checked-keys="permIds" node-key="id" />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="4">
          <el-button type="primary" size="mini" @click="btnPerm">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transformListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      showDialog: false,
      showPermissionDialog: false,
      permissionList: [],
      permIds: [],
      currentRoleId: null,
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      ruleForm: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      // 动态新增一个用于判断是否编辑的标志变量
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        // 给每个元素添加一个编辑内容
        this.$set(item, 'editRole', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    // 页码改变触发事件
    pageChange(num) {
      this.pageParams.page = num
      this.getRoleList()
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功！')
          this.btnCancel()
          // 添加成功后跳转页面到最新的一页
          this.pageParams.page = Math.ceil((this.pageParams.total + 1) / this.pageParams.pagesize)
          console.log(this.pageParams.page)
          this.getRoleList()
        }
      })
    },
    editRole(row) {
      // 开启编辑模式
      row.isEdit = true
      // 每次进入编辑模式时需将编辑内容同步给编辑内容
      row.editRole = {
        name: row.name,
        description: row.description,
        state: row.state
      }
    },
    async btnEditOK(row) {
      if (row.editRole.name && row.editRole.description) {
        // 提交表单
        await updateRole({ ...row.editRole, id: row.id })
        // 直接复制eslint会报错，所以通过对象的assign方法进行赋值
        Object.assign(row, {
          ...row.editRole,
          isEdit: false
        })
        this.$message.success('更新内容成功！')
      } else {
        this.$message.warning('角色或描述不能为空！')
      }
    },
    async delRole(id) {
      await delRole(id)
      this.$message.success('删除角色成功！')
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    async btnPermission(id) {
      this.permissionList = transformListToTreeData(await getPermissionList(), 0)
      // 记录下当前id
      this.currentRoleId = id
      // 获取当前角色的详情信息中获取已选权限的id
      const { permIds } = await getRoleDetail(id)
      // 默认设置已选权限
      this.permIds = permIds
      // 显示权限弹窗
      this.showPermissionDialog = true
    },
    async btnPerm() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
